package com.guoranhao.web.util;

import com.guoranhao.tool.utils.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Description: HttpURLConnection 文件下载
 *
 * @Version 1.0  2018/4/19.by 王红伟(wanghw@cloud-young.com) 创建
 */
public class HttpURLConnectionUtill {


    private static final Logger logger = LoggerFactory.getLogger(HttpURLConnectionUtill.class);
    /**
     * @Description: http文件下载
     * @Version 1.0  2018/4/19  9:22  by  王红伟(wanghw@coud-young.com) 创建
     */
    public static boolean  httpConnDown(String url,  String parameter, String fileDir,String fileName,String requestType){

        File file = null;
        // Post请求的url，与get不同的是不需要带参数
        URL urlParam = null;
        try {
            urlParam = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlParam.openConnection();

            //提交模式
            if("POST".equals(requestType.toUpperCase())){
                httpURLConnection.setRequestMethod("POST");
                // conn.setConnectTimeout(10000);//连接超时 单位毫秒
                // conn.setReadTimeout(2000);//读取超时 单位毫秒
                // 发送POST请求必须设置如下两行
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                // 获取URLConnection对象对应的输出流
                PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
                // 发送请求参数
                printWriter.write(parameter);//post的参数 xx=xx&yy=yy
                // flush输出流的缓冲
                printWriter.flush();
            }else{
                httpURLConnection.setRequestMethod("GET");
            }

            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            //拼接文件全路径
            StringBuilder  filePath = new StringBuilder();
            filePath.append(fileDir);
            if(!fileDir.endsWith(FilePathUtil.FILE_SEPARATOR)){
                filePath.append(File.separatorChar);
            }
            filePath.append(fileName);

            file = new File(filePath.toString());

            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }

            OutputStream out = new FileOutputStream(file);
            int size = 0;
            byte[] buf = new byte[1024];
            while((size = bin.read(buf)) != -1) {
                out.write(buf, 0, size);
               }
            bin.close();
            out.close();
            LogUtil.info(logger,"下载文件成功");
            return true;
        } catch (Exception e) {
            LogUtil.error(logger,"下载文件失败{0},文件目录{1},文件名称{2},下载url{3}",
                    e.getMessage(),fileDir,fileName,url);

        }
        return false;
    }

//    public

}
